package com.joesem.sale.client.logic.workOrder

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.core.view.forEachIndexed
import androidx.core.view.isVisible
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.jiaxing.sale.client.R
import com.jiaxing.sale.client.databinding.FragmentWorkOrderBinding
import com.joesem.sale.client.base.*
import com.joesem.sale.client.logic.event.FilterMode
import com.joesem.sale.client.logic.home.MainActivity
import com.joesem.sale.client.logic.workOrder.WorkOrderFragment.Filter.about_me
import com.joesem.sale.client.logic.workOrder.WorkOrderFragment.Filter.date_end
import com.joesem.sale.client.logic.workOrder.WorkOrderFragment.Filter.date_start
import com.joesem.sale.client.logic.workOrder.WorkOrderFragment.Filter.date_type
import com.joesem.sale.client.logic.workOrder.WorkOrderFragment.Filter.filterChange
import com.joesem.sale.client.logic.workOrder.viewModel.WorkOrderViewModel
import com.joesem.sale.client.network.data.SingleListMode
import com.joesem.sale.client.utils.click
import com.joesem.sale.client.widget.dialog.optionDatePickerRange
import com.joesem.sale.client.widget.dialog.workOrderTypePopup
import com.joesem.sale.client.widget.popup.optionSingleText

class WorkOrderFragment : BaseFragment<FragmentWorkOrderBinding>() {

    private val viewModel by createViewModel<WorkOrderViewModel>()

    private var defaultPageIndex: Int? = null//默认选择

    private var tabAttach: TabLayoutMediator? = null

    private val titles = arrayListOf(
        FilterMode(title = "未完成", code = "un_complete"),
        FilterMode(title = "待指派", code = "un_assign"),
        FilterMode(title = "已指派", code = "assigned"),
        FilterMode(title = "已接受", code = "accept"),
        FilterMode(title = "进行中", code = "process"),
        FilterMode(title = "已完成", code = "complete"),
    )

    object Filter {
        var about_me = ""
        var date_type = ""
        var date_start = ""
        var date_end = ""
        var filterChange: () -> Unit = { }

    }

    private var aboutMeFilter = SingleListMode(name = "全部工单", code = "")

    override fun FragmentWorkOrderBinding.initView(savedInstanceState: Bundle?) {
        about_me = aboutMeFilter.code
        btnFilterType.text = aboutMeFilter.name
        initAdapter()
    }

    private fun FragmentWorkOrderBinding.initAdapter() {

        vpOrderContent.adapter = object : FragmentStateAdapter(childFragmentManager, lifecycle) {

            override fun getItemCount() = titles.size

            override fun createFragment(position: Int) =
                newInstance<OrderContentFragment>(Bundle().apply {
                    putString("type", titles[position].code)
                })
        }
        tabAttach = TabLayoutMediator(
            tabTitle, vpOrderContent, true
        ) { tab, position ->
            tab.text = titles[position].title
        }
        tabAttach?.attach()
        try {
            defaultPageIndex?.let {
                vpOrderContent.postDelayed({
                    if (it < vpOrderContent.adapter?.itemCount!!) {
                        bind.vpOrderContent.currentItem = it
                        defaultPageIndex = null
                    }
                }, 300)
            }
        } catch (e: Exception) {
        }
    }


    @SuppressLint("SetTextI18n")
    override fun FragmentWorkOrderBinding.initListener() {
        lifecycle.addObserver(object : DefaultLifecycleObserver {

            override fun onResume(owner: LifecycleOwner) {
                viewModel.orderStatsNum()
                viewModel.noticeCunt()
            }

            override fun onDestroy(owner: LifecycleOwner) {
                tabAttach?.detach()
            }
        })
        btnCurrentWeek.click {
            date_type = if (btnCurrentWeek.isChecked) "week" else ""
            filterChange.invoke()
            btnCurrentMonth.isChecked = false
        }
        btnCurrentMonth.click {
            date_type = if (btnCurrentMonth.isChecked) "month" else ""
            filterChange.invoke()
            btnCurrentWeek.isChecked = false
        }

        btnFilterType.click { it ->
            optionSingleText(
                view = it, defaultSelected = aboutMeFilter, data = mutableListOf(
                    SingleListMode(name = "全部工单", code = ""),
                    SingleListMode(name = "我的部门", code = "department"),
                    SingleListMode(name = "我协助的", code = "assist"),
                    SingleListMode(name = "我负责的", code = "master"),
                    SingleListMode(name = "我创建的", code = "create"),
                )
            ) {
                about_me = it.code
                aboutMeFilter = it
                btnFilterType.text = it.name
                filterChange.invoke()
            }
        }
        btnCurrentDate.click {
            optionDatePickerRange(requireContext()) { startDate, endDate, isReset ->
                date_start = startDate
                date_end = endDate
                if (isReset) {
                    btnCurrentDate.text = "按日期"
                    btnCurrentDate.isChecked = false
                } else {
                    btnCurrentDate.text = "起 $date_start\n止 $date_end"
                    btnCurrentDate.isChecked = true
                }
                filterChange.invoke()
            }
        }
        btnAddWorkOrder.click { it ->
            workOrderTypePopup(it) {
                launch<WorkOrderCreateActivity>("type" to it)
            }
        }
        btnNotice.click {
            (requireActivity() as MainActivity).bind.bottomMenu.selectedItemId = R.id.menu_notice
        }
    }

    override fun FragmentWorkOrderBinding.initIntent(intent: Any?) {
        when (intent) {
            is WorkOrderViewModel.OrderCuntIntent -> {
                for (i in 0 until tabTitle.tabCount) {
                    val tab = tabTitle.getTabAt(i)
                    val title = titles[i].title
                    when (i) {
                        0 -> tab?.text = "$title ${intent.data.未完成}"
                        1 -> tab?.text = "$title ${intent.data.已创建}"
                        2 -> tab?.text = "$title ${intent.data.已指派}"
                        3 -> tab?.text = "$title ${intent.data.已接受}"
                        4 -> tab?.text = "$title ${intent.data.已开始}"
                        5 -> tab?.text = "$title ${intent.data.已完成}"
                    }
                }
            }
            is WorkOrderViewModel.NoticeCuntIntent -> {
                intent.data.unread?.let {
                    vNoticePoint.visibility = if (it > 0) View.VISIBLE else View.INVISIBLE
                }
            }
        }
    }

    fun pageCurrent(index: Int) {
        try {
            defaultPageIndex = index
            bind.vpOrderContent.currentItem = index
        } catch (e: Exception) {
        }
    }
}